package com.jahe.learn.nio;

import com.sun.xml.internal.ws.policy.privateutil.PolicyUtils;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author: jahe.lai
 * @create: 2019-12-24 20:31
 */
public class FileTransfer {

    public static void main(String[] args) {
        FileInputStream inputStream = null;
        FileOutputStream outputStream = null;
        try {
            inputStream = new FileInputStream("input.txt");
            outputStream = new FileOutputStream(("out.txt"));

            FileChannel inputChannel = inputStream.getChannel();
            FileChannel outChannel = outputStream.getChannel();

            ByteBuffer byteBuffer = ByteBuffer.allocate(256);

            while (true) {
                // 注释掉下面这行，会无限打印 read=0。
                // 因为buffer里有内容，所以不会返回 -1。此时buffer是有空间可写的。
                byteBuffer.clear();
                int read = inputChannel.read(byteBuffer);
                System.out.println("read="+read);
                if (-1 == read) {
                    break;
                }
                byteBuffer.flip();
                outChannel.write(byteBuffer);
            }

        } catch (IOException e0) {
            e0.printStackTrace();
        }finally {
            try {
                inputStream.close();
                outputStream.close();
            } catch (Exception e) {

            }
        }
    }
}
